<template>
  <page-dialog
    :title="dialogInfo.title"
    v-model:visible="shows"
    :width="dialogInfo.width"
    :bt-list="dialogInfo.btList"
  >
    <new-page-filter
      v-model:query="filterInfo.query"
      :clear-type="clearType"
      :filter-list="filterInfo.searchList"
      :filter-btn="filterInfo.searchBtn"
    >
    </new-page-filter>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane class="model-panel-title" label="入库资产" name="first">
        <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
          <DialogTable
            :refresh="tableInfo.refresh"
            :init-curpage="tableInfo.initCurpage"
            :query="filterInfo.query"
            v-model:data="tableInfo.data"
            :field-list="tableInfo.fieldList"
            :handle="tableInfo.handle"
            :highlight-row="highlightRow"
            :check-box="checkBox"
            :pager="false"
            @handleEvent="handleEvent"
          >
            <template v-slot:col-buildCardCalcQty="scope">
              <el-form-item @click.stop="">
                <el-input-number
                  v-model.lazy="scope.row.buildCardCalcQty"
                  style="width: 100%; margintop: 18px"
                  clearable
                  controls-position="right"
                  :precision="
                    $store.state.permission.systemConfig.qty_show_precision
                  "
                  :min="0"
                  :max="scope.row.canBuildCardCalcQty"
                />
              </el-form-item>
            </template>
          </DialogTable>
        </el-form>
      </el-tab-pane>
      <el-tab-pane class="model-panel-title" label="收货资产" name="second">
        <el-form
          :model="tableInfo"
          ref="tableFormReceiving"
          style="width: 100%"
        >
          <DialogTable
            :refresh="tableInfo.refresh"
            :init-curpage="tableInfo.initCurpage"
            :query="filterInfo.query"
            v-model:data="tableInfo.data"
            :field-list="tableInfo.fieldList"
            :handle="tableInfo.handle"
            :highlight-row="highlightRow"
            :check-box="checkBox"
            :pager="false"
            @handleEvent="handleEventReceiving"
          >
            <template v-slot:col-buildCardCalcQty="scope">
              <el-form-item @click.stop="">
                <el-input-number
                  v-model.lazy="scope.row.buildCardCalcQty"
                  style="width: 100%; margintop: 18px"
                  clearable
                  controls-position="right"
                  :precision="
                    $store.state.permission.systemConfig.qty_show_precision
                  "
                  :min="0"
                  :max="scope.row.canBuildCardCalcQty"
                />
              </el-form-item>
            </template>
          </DialogTable>
        </el-form> </el-tab-pane
    ></el-tabs>
  </page-dialog>
</template>
<script setup name="buildCard">
import {
  getCanCreateCarByAssetStore,
  getCanCreateCarByAssetReceiving,
} from '@/api/asset'
import { checkBuildNumberForAssetCard } from '@/api/core'
import _ from 'lodash'
const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps({
  highlightRow: {
    type: Boolean,
    default: true,
  },
  checkBox: {
    type: Boolean,
    default: true,
  },
  visible: {
    type: Boolean,
    default: false,
  },
})

const activeName = ref('first')
// 过滤相关配置
const filterInfo = ref({
  copyQuery: {},
  query: {
    keyword: '',
  },
  searchList: [
    {
      componentType: 'input',
      label: '资产名称/单号',
      value: 'keyword',
      event: search,
    },
  ],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '重置', event: clearSearch },
  ],
})
const clearType = ref(true)
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: getCanCreateCarByAssetStore,
  fieldList: [
    { label: '资产名称', value: 'commonName' },
    { label: '资产字典编码', value: 'productCode' },
    { label: '单号', value: 'orderNo' },
    { label: '资产分类', value: 'assetTypeValue' },
    { label: '资产财务分类', value: 'financeTypeValue' },
    { label: '部门', value: 'deptName', hidden: true },
    { label: '仓库', value: 'depotName', hidden: false },
    { label: '供应商', value: 'supplierName' },
    { label: '总数量', value: 'qty' },
    { label: '可建卡数量', value: 'canBuildCardCalcQty' },
    { label: '建卡数量', value: 'buildCardCalcQty', type: 'slot' },
  ],
})
// 弹窗相关
const dialogInfo = ref({
  title: '批量建卡',
  width: '80%',
  btLoading: false,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    { label: '保存', event: handleSave, show: true },
  ],
})
const selectRow = ref([])
const selectRowReceiving = ref([])
const shows = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})
onMounted(() => {
  filterInfo.value.copyQuery = proxy.$fn.deepClone(filterInfo.value.query)
  getList(1)
})
function search() {
  if (activeName.value == 'first') {
    getList(1)
  } else if (activeName.value == 'second') {
    getList(2)
  }
}
function clearSearch() {
  filterInfo.value.query.keyword = ''
  clearType.value = !clearType.value
  search()
}
function showFieldListItem(show, nameValue) {
  let fieldList = tableInfo.value.fieldList
  fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.hidden = show
    }
  })
}
function handleClick(tab) {
  const name = tab.paneName
  if (name == 'first') {
    getList(1)
    showFieldListItem(false, 'depotName')
    showFieldListItem(true, 'deptName')
  } else if (name == 'second') {
    getList(2)
    showFieldListItem(true, 'depotName')
    showFieldListItem(false, 'deptName')
  }
}
function getList(val) {
  let api = null
  if (val === 1) {
    api = getCanCreateCarByAssetStore
  } else if (val === 2) {
    api = getCanCreateCarByAssetReceiving
  }
  tableInfo.value.refresh = Math.random()
  api(filterInfo.value.query).then((res) => {
    if (res && res.success) {
      tableInfo.value.data = res.data.map((item) => {
        item.buildCardCalcQty = item.canBuildCardCalcQty
        return item
      })
    }
  })
}
function handleEvent(event, data) {
  if (event === 'tableCheck') {
    selectRow.value = data
  }
}
function handleEventReceiving(event, data) {
  if (event === 'tableCheck') {
    selectRowReceiving.value = data
  }
}
function handleSave() {
  if (selectRow.value.length && selectRowReceiving.value.length) {
    proxy.$message.warning('只能选择一种类型！')
    return
  }
  let data = []
  if (selectRow.value.length) {
    data = selectRow.value
  } else if (selectRowReceiving.value.length) {
    data = selectRowReceiving.value
  } else {
    proxy.$message.warning('请选择资产！')
    return
  }
  let copyArr = proxy.$fn.deepClone(data)
  if (data.length > 1) {
    let productIds = copyArr.map((item) => item.productId)
    let uniqArr = [...new Set(productIds)]
    if (uniqArr.length > 1) {
      proxy.$message.warning('请选择相同的资产！')
      return
    }
    let supplierIds = copyArr.map((item) => item.supplierId)
    let supplierUniqArr = [...new Set(supplierIds)]
    if (supplierUniqArr.length > 1) {
      proxy.$message.warning('选择的资产是不同的供应商！')
      return
    }
  }
  let msgFlag = false
  data.forEach((item) => {
    if (!item.buildCardCalcQty) {
      msgFlag = true
    }
  })
  if (msgFlag) {
    proxy.$message.warning('选择的资产建卡数量应大于0！')
    return
  }
  if (data.length > 1 && activeName.value === 'first') {
    let _uniqArr = _.uniqBy(copyArr, 'depotName')
    if (data.length === _uniqArr.length) {
      proxy.$message.warning('选择的资产是不同的仓库！')
      return
      // proxy
      //   .$confirm(
      //     '所选数据存在不同仓库的资产，批量建卡后会更新数据，是否继续？',
      //     '提示',
      //     {
      //       confirmButtonText: '确定',
      //       cancelButtonText: '取消',
      //       type: 'warning',
      //     }
      //   )
      //   .then(() => {
      //     checkBuild(data)
      //   })
    } else {
      checkBuild(data)
    }
  } else if (data.length > 1 && activeName.value === 'second') {
    let _uniqArr = _.uniqBy(copyArr, 'deptName')
    if (data.length === _uniqArr.length) {
      proxy.$message.warning('选择的资产是不同的部门！')
      return
      // proxy
      //   .$confirm(
      //     '所选数据存在不同部门的资产，批量建卡后会更新数据，是否继续？',
      //     '提示',
      //     {
      //       confirmButtonText: '确定',
      //       cancelButtonText: '取消',
      //       type: 'warning',
      //     }
      //   )
      //   .then(() => {
      //     checkBuild(data)
      //   })
    } else {
      checkBuild(data)
    }
  } else {
    checkBuild(data)
  }
}
function checkBuild(data) {
  let obj = {}
  obj.orderDetail = data.map((item) => {
    return {
      orderId: item.id,
      qty: item.buildCardCalcQty,
    }
  })
  obj.productId = data[0].productId
  if (data[0].increaseType === 0 || data[0].increaseType) {
    //入库资产
    obj.orderSourceType = 66
  } else {
    //收货资产
    obj.orderSourceType = 15
  }
  checkBuildNumberForAssetCard(obj).then((res) => {
    if (res && res.success) {
      proxy.$message.closeAll()
      shows.value = false
      emits('callback', data)
    }
  })
}
// 关闭弹窗前的回调
function handleClose() {
  shows.value = false
}
</script>
<style scoped lang="scss"></style>
